package com.chinameyer.workorders.controller;

import com.chinameyer.workorders.bean.MeyerStaff;
import com.chinameyer.workorders.dto.staff.AddStaffDTO;
import com.chinameyer.workorders.dto.staff.EditStaffDTO;
import com.chinameyer.workorders.service.StaffService;
import com.xinmachong.response.ApiResponse;
import com.xinmachong.response.ApiResponseWithPage;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.Min;
import java.util.List;

/**
 * @Author meyer@HongYe
 */
@RestController
@RequestMapping("/v1/staff")
@Validated
@CrossOrigin
public class StaffController {

    @Resource
    private StaffService staffService;


    @PostMapping("/add")
    public ApiResponse add(@RequestBody @Validated AddStaffDTO addStaffDTO) {
        boolean isExist = this.staffService.checkStaffIsExist(addStaffDTO);
        if (isExist) {
            return new ApiResponse(400,"当前员工已存在，请勿重复添加",0);
        }
        try {
            this.staffService.addStaff(addStaffDTO);
            return new ApiResponse(200, "success", 1);
        } catch (Exception e) {
            return new ApiResponse(400,"员工添加失败，请重新添加或者联系系统管理员",0);
        }
    }


    @DeleteMapping("/delete")
    public ApiResponse delete(@RequestParam(value = "staffId") Integer staffId) {
        try {
            this.staffService.deleteStaff(staffId);
            return new ApiResponse(200, "success", 1);
        } catch (Exception e) {
            return new ApiResponse(400,"员工删除失败",0);
        }
    }


    @PostMapping("update")
    public ApiResponse update(@RequestBody @Validated EditStaffDTO editStaffDTO) {
        boolean isExist = this.staffService.checkStaffIsExistExpectItself(editStaffDTO);
        if (isExist) {
            return new ApiResponse(400,"当前员工已存在",0);
        }
        try {
            this.staffService.updateStaff(editStaffDTO);
            return new ApiResponse(200, "success", 1);
        } catch (Exception e) {
            return new ApiResponse(400,"员工更新失败，请重新更新或者联系系统管理员",0);
        }
    }


    @GetMapping("/getAll")
    public ApiResponseWithPage getAll(@RequestParam(value = "catalogueId") Integer catalogueId,
                                      @RequestParam(name = "count", required = false, defaultValue = "10")
                                      @Min(value = 1, message = "分页数量必须为正整数") Integer count,
                                      @RequestParam(name = "page", required = false, defaultValue = "1")
                                      @Min(value = 0, message = "分页必须为正整数") Integer page) {
        List<MeyerStaff> staffList = this.staffService.getAllStaff(catalogueId,count,page - 1);
        int total = this.staffService.getAllStaffTotal(catalogueId);
        return new ApiResponseWithPage(200,"success",staffList,total);
    }
}
